import org.grails.plugins.springsecurity.service.AuthenticateService

class CommentController {
	
	AuthenticateService authenticateService
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        [ commentInstanceList: Comment.list( params ) ]
    }

    def show = {
        def commentInstance = Comment.get( params.id )

        if(!commentInstance) {
            flash.message = "Comment not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ commentInstance : commentInstance ] }
    }

    def delete = {
        def commentInstance = Comment.get( params.id )
        if(commentInstance) {
            commentInstance.delete()
            flash.message = "Comment ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Comment not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def commentInstance = Comment.get( params.id )

        if(!commentInstance) {
            flash.message = "Comment not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ commentInstance : commentInstance ]
        }
    }

    def update = {
        def commentInstance = Comment.get( params.id )
        if(commentInstance) {
            commentInstance.properties = params
            if(!commentInstance.hasErrors() && commentInstance.save()) {
                flash.message = "Comment ${params.id} updated"
                redirect(action:show,id:commentInstance.id)
            }
            else {
                render(view:'edit',model:[commentInstance:commentInstance])
            }
        }
        else {
            flash.message = "Comment not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def commentInstance = new Comment()
        commentInstance.properties = params
        commentInstance.artifact = Artifact.get(params.artfId)
        commentInstance.creator = authenticateService.userDomain()
        return ['commentInstance':commentInstance]
    }

    def save = {
        def commentInstance = new Comment(creator:User.get(params.creator), 
	    									artifact:Artifact.get(params.artifact), 
	    									body:params.body, 
	    									creationDate: new Date());
        
        if(!commentInstance.hasErrors() && commentInstance.save()) {
            flash.message = "Comment ${commentInstance.id} created"
            redirect(action:show,id:commentInstance.id)
        }
        else {
            render(view:'create',model:[commentInstance:commentInstance])
        }
    }
}
